package com.silong.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * 实体类转map
 * Created by magy on 2016/7/2.
 */
public class BeanToMap {
    /**
     * 实体类转map
     * @param obj
     * @return
     */
    public static Map ConvertObjToMap(Object obj){
        Map<String,String> reMap = new HashMap<String,String>();
        if (obj == null)
            return null;
        Field[] fields = obj.getClass().getDeclaredFields();
        try {
            for(int i=0;i<fields.length;i++){
                try {
                    Field f = obj.getClass().getDeclaredField(fields[i].getName());
                    f.setAccessible(true);
                    String o = f.get(obj).toString();
                    reMap.put(fields[i].getName(), o);
                } catch (NoSuchFieldException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return reMap;
    }

    public static Object objectToMap(Map<String, Object> map, Class<?> clazz, boolean valueConvertToString) throws Exception {
        Field[] fields = clazz.getDeclaredFields();
        Object object = clazz.getDeclaredConstructor().newInstance();
        for(Map.Entry<String, Object> entry : map.entrySet()){
            for (Field f : fields) {
                f.setAccessible(true);
                if(entry.getKey().equals(f.getName())){
                    f.set(object, valueConvertToString ? entry.getValue().toString() : entry.getValue());
                }
            }

        }
        return object;
    }

    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null)
            return null;

        Object obj = beanClass.newInstance();

        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
                continue;
            }

            field.setAccessible(true);
            field.set(obj, map.get(field.getName()));
        }

        return obj;
    }
}
